﻿namespace Pub.Class
{
    using System;
    using System.Collections;
    using System.Drawing;
    using System.IO;
    using System.IO.Compression;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Security.Cryptography;
    using System.Text;

    public static class ArrayExtensions
    {
        public static byte[] DeflateCompress(this byte[] Bytes)
        {
            byte[] buffer;
            if (Bytes.IsNull())
            {
                throw new ArgumentNullException("Bytes");
            }
            using (MemoryStream stream = new MemoryStream())
            {
                using (DeflateStream stream2 = new DeflateStream(stream, CompressionMode.Compress, true))
                {
                    stream2.Write(Bytes, 0, Bytes.Length);
                    stream2.Close();
                    buffer = stream.ToArray();
                }
            }
            return buffer;
        }

        public static byte[] DeflateDecompress(this byte[] Bytes)
        {
            byte[] buffer2;
            if (Bytes.IsNull())
            {
                throw new ArgumentNullException("Bytes");
            }
            using (MemoryStream stream = new MemoryStream())
            {
                using (DeflateStream stream2 = new DeflateStream(new MemoryStream(Bytes), CompressionMode.Decompress, true))
                {
                    byte[] buffer = new byte[0x1000];
                    while (true)
                    {
                        int count = stream2.Read(buffer, 0, buffer.Length);
                        if (count <= 0)
                        {
                            break;
                        }
                        stream.Write(buffer, 0, count);
                    }
                    stream2.Close();
                    buffer2 = stream.ToArray();
                }
            }
            return buffer2;
        }

        [DllImport("urlmon.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
        private static extern int FindMimeFromData(IntPtr pBC, [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl, [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)] byte[] pBuffer, int cbSize, [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed, int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved);
        public static T FromBinary<T>(this byte[] data)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream(data))
            {
                return (T) formatter.Deserialize(stream);
            }
        }

        public static T FromDeflateDecompressBinary<T>(this byte[] compressedData) where T: class
        {
            return compressedData.DeflateDecompress().FromBinary<T>();
        }

        public static Encoding GetEncoding(this byte[] data)
        {
            if (data[0] >= 0xef)
            {
                if (((data[0] == 0xef) && (data[1] == 0xbb)) && (data[2] == 0xbf))
                {
                    return Encoding.UTF8;
                }
                if ((data[0] == 0xfe) && (data[1] == 0xff))
                {
                    return Encoding.BigEndianUnicode;
                }
                if ((data[0] == 0xff) && (data[1] == 0xfe))
                {
                    return Encoding.Unicode;
                }
            }
            return Encoding.Default;
        }

        public static Encoding GetHtmlEncoding(this byte[] bytes, Encoding defaultEncoding)
        {
            Encoding htmlEncoding = Encoding.ASCII.GetString(bytes).GetHtmlEncoding(null);
            if (!htmlEncoding.IsNull())
            {
                return htmlEncoding;
            }
            if (bytes.Length > 3)
            {
                if ((bytes[0] == 0xff) && (bytes[1] == 0xfe))
                {
                    return Encoding.Unicode;
                }
                if (((bytes[0] == 0xef) && (bytes[1] == 0xbb)) && (bytes[2] == 0xbf))
                {
                    return Encoding.UTF8;
                }
                return defaultEncoding;
            }
            return defaultEncoding;
        }

        public static string GetImageExtension(this byte[] fileData)
        {
            if (fileData.IsNull() || (fileData.Length < 10))
            {
                return null;
            }
            if (((fileData[0] == 0x47) && (fileData[1] == 0x49)) && (fileData[2] == 70))
            {
                return "GIF";
            }
            if (((fileData[1] == 80) && (fileData[2] == 0x4e)) && (fileData[3] == 0x47))
            {
                return "PNG";
            }
            if (((fileData[6] == 0x4a) && (fileData[7] == 70)) && ((fileData[8] == 0x49) && (fileData[9] == 70)))
            {
                return "JPG";
            }
            if ((fileData[0] == 0x42) && (fileData[1] == 0x4d))
            {
                return "BMP";
            }
            return string.Empty;
        }

        public static int GetInArrayID(this string[] stringArray, string strSearch)
        {
            return stringArray.GetInArrayID(strSearch, true);
        }

        public static int GetInArrayID(this string[] stringArray, string strSearch, bool caseInsensetive)
        {
            for (int i = 0; i < stringArray.Length; i++)
            {
                if (caseInsensetive)
                {
                    if (strSearch.ToLower() == stringArray[i].ToLower())
                    {
                        return i;
                    }
                }
                else if (strSearch == stringArray[i])
                {
                    return i;
                }
            }
            return -1;
        }

        public static string GetMimeType(this byte[] data)
        {
            if (data.Length == 0)
            {
                return "application/unknown";
            }
            IntPtr ppwzMimeOut = new IntPtr();
            int errorCode = FindMimeFromData(IntPtr.Zero, string.Empty, data, data.Length, null, 0, out ppwzMimeOut, 0);
            if (errorCode != 0)
            {
                throw Marshal.GetExceptionForHR(errorCode);
            }
            string str = Marshal.PtrToStringUni(ppwzMimeOut);
            Marshal.FreeCoTaskMem(ppwzMimeOut);
            return str;
        }

        public static byte[] GZipCompress(this byte[] Bytes)
        {
            byte[] buffer;
            if (Bytes.IsNull())
            {
                throw new ArgumentNullException("Bytes");
            }
            using (MemoryStream stream = new MemoryStream())
            {
                using (GZipStream stream2 = new GZipStream(stream, CompressionMode.Compress, true))
                {
                    stream2.Write(Bytes, 0, Bytes.Length);
                    stream2.Close();
                    buffer = stream.ToArray();
                }
            }
            return buffer;
        }

        public static byte[] GZipDecompress(this byte[] Bytes)
        {
            byte[] buffer2;
            if (Bytes.IsNull())
            {
                throw new ArgumentNullException("Bytes");
            }
            using (MemoryStream stream = new MemoryStream())
            {
                using (GZipStream stream2 = new GZipStream(new MemoryStream(Bytes), CompressionMode.Decompress, true))
                {
                    byte[] buffer = new byte[0x1000];
                    while (true)
                    {
                        int count = stream2.Read(buffer, 0, buffer.Length);
                        if (count <= 0)
                        {
                            break;
                        }
                        stream.Write(buffer, 0, count);
                    }
                    stream2.Close();
                    buffer2 = stream.ToArray();
                }
            }
            return buffer2;
        }

        public static bool IsImage(this byte[] fileData)
        {
            return fileData.GetImageExtension().IsInArray("GIF,PNG,JPG,BMP", ",");
        }

        public static bool IsInArray(this string[] stringarray, string str)
        {
            return stringarray.IsInArray(str, false);
        }

        public static bool IsInArray(this string[] stringArray, string strSearch, bool caseInsensetive)
        {
            return (stringArray.GetInArrayID(strSearch, caseInsensetive) >= 0);
        }

        public static bool IsNullEmpty(this Array array)
        {
            if (!array.IsNull())
            {
                return (array.Length == 0);
            }
            return true;
        }

        public static bool IsNullEmpty(this ArrayList list)
        {
            if (!list.IsNull())
            {
                return (list.Count == 0);
            }
            return true;
        }

        public static bool IsUnicode(this byte[] Input)
        {
            if (!Input.IsNull())
            {
                UnicodeEncoding encoding = new UnicodeEncoding();
                byte[] bytes = encoding.GetBytes(encoding.GetString(Input));
                ASCIIEncoding encoding2 = new ASCIIEncoding();
                byte[] buffer2 = encoding2.GetBytes(encoding2.GetString(Input));
                if (bytes[0] == buffer2[0])
                {
                    return false;
                }
            }
            return true;
        }

        public static string Join<T>(this T[] array, string splitStr)
        {
            StringBuilder builder = new StringBuilder();
            foreach (T local in array)
            {
                builder.AppendFormat("{0}{1}", local.ToString(), splitStr);
            }
            return builder.ToString().Left((builder.Length - splitStr.Length));
        }

        public static string MD5(this byte[] bts)
        {
            if (bts.IsNull() || (bts.Length == 0))
            {
                return null;
            }
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            new UTF8Encoding();
            byte[] buffer = provider.ComputeHash(bts);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(string.Format("{0:x2}", buffer[i]));
            }
            return builder.ToString();
        }

        public static T[] RemoveDuplicates<T>(this T[] array)
        {
            ArrayList list = new ArrayList();
            for (int i = 0; i < array.Length; i++)
            {
                if (!list.Contains(array[i]))
                {
                    list.Add(array[i]);
                }
            }
            return (T[]) list.ToArray(typeof(T));
        }

        public static T[] Slice<T>(this T[] array, int start, int end)
        {
            if (start >= array.Length)
            {
                start = 0;
                end = 0;
            }
            if (end < 0)
            {
                end = (array.Length - start) - end;
            }
            if (end <= start)
            {
                end = start;
            }
            if (end >= array.Length)
            {
                end = array.Length - 1;
            }
            int num = (end - start) + 1;
            T[] localArray = new T[num];
            for (int i = 0; i < num; i++)
            {
                localArray[i] = array[i + start];
            }
            return localArray;
        }

        public static string ToBase64(this byte[] data)
        {
            return Convert.ToBase64String(data);
        }

        public static bool ToFile(this byte[] bytes, string fileName, FileMode fileMode)
        {
            bool flag = true;
            FileAccess readWrite = FileAccess.ReadWrite;
            if (fileMode == FileMode.Append)
            {
                readWrite = FileAccess.Write;
            }
            FileStream output = new FileStream(fileName, fileMode, readWrite);
            BinaryWriter writer = new BinaryWriter(output);
            try
            {
                writer.Write(bytes);
            }
            catch (Exception)
            {
                flag = false;
            }
            finally
            {
                output.Close();
                writer.Close();
            }
            return flag;
        }

        public static string ToHexString(this byte[] data)
        {
            StringBuilder builder = new StringBuilder(data.Length * 3);
            foreach (byte num in data)
            {
                builder.Append(Convert.ToString(num, 0x10).PadLeft(2, '0').PadRight(3, ' '));
            }
            return builder.ToString().ToUpper();
        }

        public static Image ToImage(this byte[] bytes)
        {
            if (bytes.IsNotNull())
            {
                MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length);
                stream.Write(bytes, 0, bytes.Length);
                return Image.FromStream(stream, true);
            }
            return null;
        }

        public static string ToUTF8(this byte[] characters)
        {
            return new UTF8Encoding().GetString(characters);
        }
    }
}

